<script setup>
import {onMounted, ref} from 'vue';
import {addCategory, deleCategory, editCategory, getCategoryPage, queryCategory} from '@/apis/category.js';
import {Plus,Search} from "@element-plus/icons-vue";
import {uploadImg} from "@/apis/common.js";
import {formatTime} from "@/utils/time_common.js";


const total = ref(0);
const current = ref(1);
const size = ref(10);
const queryName = ref('');
const tableData = ref([]);
const drawer = ref(false)
const uploadRef = ref()
const classData = ref({
  title: '',
  id: '',
  name: '',
  img: '',
  action: '',
  remarks: ''
});
const fileList = ref([])
const VITE_IMG_UPLOAD_PATH = import.meta.env.VITE_IMG_UPLOAD_PATH
const VITE_BASE_URL = import.meta.env.VITE_BASE_URL
let Authorization = {Authorization: localStorage.getItem("accessToken")}
const init = async () => {
  await getCategoryPage({current: current.value, size: size.value}).then((res) => {
    if (res.data.code === 1) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      // Handle error
      console.log(res.data.msg)
    }
  }).catch((err) => {
    // Handle error
    console.log(err);
  });
};

const handleQuery = () => {
  current.value = 1;
  init();
};

const findHandle = () => {
  const params = {
    name: queryName.value,
    current: current.value,
    size: size.value,
  };
  queryCategory(params).then((res) => {
    if (res.data.code === 1) {
      // Handle success
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    } else {
      // Handle error
      ElMessage(res.data.msg)
    }
  }).catch((err) => {
    // Handle error
  });
};

function formatUpdateTime(row) {
  return formatTime(row.updateTime);
}

const addHandle = () => {
  classData.value.title = '新增分类';
  classData.value.action = 'add';
  classData.value.name = '';
  classData.value.img = '';
  classData.value.remarks = '';
  drawer.value = true;
};

const editHandle = (dat) => {
  classData.value.action = 'edit';
  classData.value.name = dat.name;
  classData.value.img = dat.img;
  classData.value.id = dat.id;
  classData.value.remarks = dat.remarks;
  drawer.value = true;
};

const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    done();
  }).catch(() => {
  });
};

const deleteHandle = (id) => {
  const confirmText = '此操作将永久删除该分类, 是否继续?';
  const confirmTitle = '提示';
  const confirmType = 'warning';

  ElMessageBox.confirm(confirmText, confirmTitle, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: confirmType,
  }).then(() => {
    deleCategory(id).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
      } else {
        // Handle error
      }
    }).catch((err) => {
      // Handle error
    });
  });
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M!')
    return false
  }
  return true
}

// 上传图片，把图片先缓存在浏览器本地，然后再上传
const handleChange = (file) => {
  const reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = (e) => {
    classData.value.img = e.target.result;
  };
}

// 上传图片
const uploadIcon = async () => {
  await uploadImg(classData.value.img).then((res) => {
    if (res.code === 1) {
      classData.value.img = res.data.url;
      console.log(classData.value.img)
    } else {
      this.$message.error(res.msg || '操作失败');
    }
  }).catch((err) => {
        this.$message.error('请求出错了：' + err);
      }
  );
}

// 图片上传成功回调
const uploadSuccess = (res) => {
  // 得到返回的图片地址
  classData.value.img = res.data;
  console.log('图片成功回调')
  submitCategory()
}


const submitForm = async () => {
  const valid = (classData.value.name === null || classData.value.name) && (classData.value.img === null || classData.value.img);
  if (valid) {
    if (classData.value.img.startsWith("data:image/")) {
      uploadRef.value.submit()
    } else
      submitCategory()
  } else {
    ElMessage.error('请填写完整信息！');
  }
};
// 执行添加或者编辑
const submitCategory = () => {
  if (classData.value.action === 'add') {
    console.log('正在添加')
    addCategory(classData.value).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
        drawer.value = false;
        ElMessage.success('添加成功')

      } else {
        // Handle error
        ElMessage(res.data.msg)
      }
    }).catch((err) => {
      // Handle error
    });
  } else {
    editCategory(classData.value).then((res) => {
      if (res.data.code === 1) {
        // Handle success
        handleQuery();
        drawer.value = false;
        ElMessage.success('修改成功')
      } else {
        // Handle error
        ElMessage(res.data.msg)
      }
    }).catch((err) => {
      // Handle error
    });
  }
  classData.value = {
    title: '',
    id: '',
    name: '',
    img: '',
    action: '',
    remarks: ''
  }
};

const currentChange = (val) => {
  current.value = val;
  init();
};

onMounted(() => {
  init();
});
</script>

<template>
  <div id="category-app" class="dashboard-container">
    <div class="container">
      <div class="tableBar">
        <el-form :inline="true">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="queryName" clearable placeholder="请输入分类名称"></el-input>
          </el-form-item>
          <el-form-item label-width="0" prop="find">
            <el-button :icon="Search" type="primary" @click="findHandle">查询</el-button>
          </el-form-item>
          <el-form-item label-width="0" prop="add">
            <el-button :icon="Plus" type="primary" @click="addHandle">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="tableData" class="tableBox" stripe>
        <el-table-column label="分类ID" prop="id"></el-table-column>
        <el-table-column label="分类名称" prop="name"></el-table-column>
        <el-table-column :formatter="formatUpdateTime" label="操作时间" prop="updateTime"></el-table-column>
        <el-table-column label="修改人" prop="updateUser"></el-table-column>
        <el-table-column label="分类图标" prop="img">
          <template v-slot="{ row }">
            <img :src="`${row.img}`" alt="" width="50">
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks">
        </el-table-column>
        <el-table-column align="center" label="操作" width="160">
          <template v-slot="{ row }">
            <el-button class="blueBug" size="small" type="text" @click="editHandle(row)">修改</el-button>
            <el-button class="delBut" size="small" type="text" @click="deleteHandle(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="current" :total=total background class="pageList" layout="prev, pager, next"
                     @current-change="currentChange"/>
    </div>
    <el-drawer v-model=drawer :before-close="handleClose" :title="分类详情" size="50%">
      <el-form class="demo-form-inline" label-width="100px">
        <el-form-item label="分类名称：">
          <el-input v-model="classData.name" maxlength="14" placeholder="请输入分类名称"/>
        </el-form-item>
        <el-form-item height="100px" label="分类的图标：" width="120px">
          <el-upload
              ref="uploadRef"
              :auto-upload=false
              :before-upload="beforeAvatarUpload"
              :file-list="fileList"
              :multiple="false"
              :headers="Authorization"
              :on-change="handleChange"
              :on-success="uploadSuccess"
              :show-file-list="false"
              accept=".png, .jpg, .jpeg"
              :action=VITE_IMG_UPLOAD_PATH
              class="avatar-uploader"
              list-type="picture-card"
          >
            <img v-if="classData.img" :src="classData.img" alt="" class="avatar"/>
            <el-icon v-else color=red>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="classData.remarks" maxlength="14" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item slot="footer" class="drawer-footer">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="submitForm()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<style scoped>
@import "@/styles/common.css";
@import "@/styles/page.css";

#category-app {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

.tableBox {
  width: 100%;
}

.tableBar {
  padding: 10px 0;
  text-align: center;
}

.pageList {
  margin: 20px 0;
  text-align: center;
}

.drawer-footer {
  display: flex;
  justify-content: space-between;
}

.continue {
  margin-left: 10px;
}

.blueBug {
  color: #409EFF;
}

.delBut {
  color: #FF4949;
}


.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>